let logDom = $('#log>div.log')
let statusDom = $('#log>div.status')
let cfgDom = $('#config>form')


function clr() {
    logDom.children().remove()
}
function op(fn) {
    fn().then(data => {
        data = $.parseJSON(data)
        console.log(data)
    })
}

function createReq() {
    layer.open({
        type: 2,
        title: '创建请求',
        maxmin: true,
        shade: 0,
        area: ['800px', '500px'],
        content: '/create_req.html',
        end: function(){}
    })
}
function log(msg) {
    // 超过 500 条删除最后 200 条
    if (logDom.children() && logDom.children().length > 500) {
        logDom.children("div:gt(" + (logDom.children().length - 201) + ")").remove()
    }
    // 新日志写在前面
    msg = Base64.decode(msg)
    msg = msg.replace(/^(\[.*?\]) ([A-Z0-9_]*) (.*)/,
        '<span class="log-from">$1</span><span class="log-msgtype">$2</span>'+
        '<button class="log-copy button blue">复制</button><span class="log-content">$3</span>')
    logDom.prepend($('<div></div>', {html: msg,class:"log-info"}))
    return msg
}
function UIChangeStatus(state) {
    statusDom.html(state)
}

function cfg() {
    gniPlayCfg().then(data => {
        let cfg = $.parseJSON(data)
        if (cfg) {
            cfgDom.children().remove()
            for (let k in cfg) {
                cfgDom.append(createInput(k, cfg[k], k))
            }
        }
    })
}

function connect() {
    let rst = formToJson(cfgDom)
    gniCliConnect(rst).then(data => {
        data = $.parseJSON(data)
        if (data.Code !== 0) {
            log(data.Msg)
        }
    })
}


function refreshReqShortcuts(dom) {
    let rs = GetReqShortcuts()
    dom.children().remove()
    for (let idx in rs) {
        dom.append(createReqInput(rs[idx], idx))
    }
}